﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DevExpress.XtraPrinting.Native;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcDisplayEquipOnMap : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["d"]))
                {
                    int temp = Convert.ToInt32(Request.QueryString["d"]);
                    if (temp == 0)
                    {
                        //LoadGrlSensor();
                        DisplaySensorAll();
                        grlDuAn.Visible = false;
                        grlSensor.Visible = true;
                        CbChoiceLayer.SelectedIndex = 0;
                    }
                    else
                    {
                        //LoadGrlDuAn();
                        DisplayDuan();
                        grlSensor.Visible = false;
                        grlDuAn.Visible = true;
                        CbChoiceLayer.SelectedIndex = 1;
                    }

                }
                else
                {
                    //LoadGrlSensor();
                    DisplaySensorAll();
                    grlDuAn.Visible = false;
                    grlSensor.Visible = true;
                    CbChoiceLayer.SelectedIndex = 0;
                }
               
            }
            else
            {
                if (CbChoiceLayer.SelectedIndex == 0)
                {
                    if (Session[SessionConst.SES_GRL_SENSOR] != null &&
                        Session[SessionConst.SES_HD_FIELD_SENSOR] != null)
                    {
                        grlSensor.DataSource = Session[SessionConst.SES_GRL_SENSOR];
                        TextSource.Value = Session[SessionConst.SES_HD_FIELD_SENSOR].ToString();
                    }
                   /* else
                    {
                        LoadGrlSensor();
                        DisplaySensorAll();
                        grlDuAn.Visible = false;
                        grlSensor.Visible = true;
                        CbChoiceLayer.SelectedIndex = 0;
                    }*/
                }
                else
                {
                    if (Session[SessionConst.SES_GRL_DUAN] != null &&
                        Session[SessionConst.SES_HD_FIELD_DUAN] != null)
                    {
                        grlDuAn.DataSource = Session[SessionConst.SES_GRL_DUAN];
                        ProjectList.Value = Session[SessionConst.SES_HD_FIELD_DUAN].ToString();
                    }
                   /* else
                    {
                        LoadGrlDuAn();
                        DisplayDuan();
                        grlSensor.Visible = false;
                        grlDuAn.Visible = true;
                        CbChoiceLayer.SelectedIndex = 1;
                    }*/
                } 
            }
        }
        protected void LoadGrlSensor()
        {
            string nsd = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var data = (from s in DaoHelper.Entities.Sensors
                        join i in DaoHelper.Entities.ThietBis on s.MaThietBi equals i.MaThietBi
                        join d in DaoHelper.Entities.DuAns on i.MaDuAn equals d.MaDuAn
                        join q in DaoHelper.Entities.PhanQuyenDuAns on d.MaDuAn equals q.MaDuAn
                        where (q.UserName == nsd && i.Status == 0)
                        select new { s.MaSensor, s.TenSensor, s.MoTa }).ToList();
            Session[SessionConst.SES_GRL_SENSOR] = data;
            grlSensor.DataSource = data;
            grlSensor.DataBind();

            
        }
        protected void LoadGrlDuAn()
        {
            string nsd = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            List<DuAn> data = (from p in DaoHelper.Entities.PhanQuyenDuAns
                               join d in DaoHelper.Entities.DuAns on p.MaDuAn equals d.MaDuAn
                               where p.UserName == nsd
                               select d
                ).ToList();

            Session[SessionConst.SES_GRL_DUAN] = data;
            grlDuAn.DataSource = data;
            grlDuAn.DataBind();
        }
        protected void DisplaySensorAll()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            #region Sensor
            var list = (from s in DaoHelper.Entities.Sensors
                        join h in DaoHelper.Entities.SensorLatestValues on s.MaSensor equals h.MaSensor
                        join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                        join q in DaoHelper.Entities.PhanQuyenDuAns on t.MaDuAn equals q.MaDuAn
                        join a in DaoHelper.Entities.DuAns on q.MaDuAn equals a.MaDuAn
                      
                        where (q.UserName == us && t.Status == 0)
                        select new
                        {
                            s.TenSensor,
                            s.MaSensor,
                            h.GiaTri,
                            h.ThoiGianDo,
                            t.TenThietBi,
                            t.MaThietBi,
                            q.MaDuAn,
                            a.TenDuAn,
                            s.Latitude,
                            s.Longitude,
                            t.Status,
                            s.MoTa
                        }).ToList();

            Session[SessionConst.SES_GRL_SENSOR] = list;
            grlSensor.DataSource = list;
            grlSensor.DataBind();

            string listInputText = "";
            string inputText = "";

            foreach (var sensor in list)
            {
                inputText = "";
                inputText += sensor.TenDuAn + "µ";//0
                inputText += sensor.TenThietBi + "µ";//1
                inputText += sensor.TenSensor + "µ";//2
                if( sensor.GiaTri.Equals(-999))
                {
                    inputText += "Chưa có giá trịµ";
                    inputText += "Chưa có giá trịµ";
                }
                else
                {
                    inputText += sensor.GiaTri + "µ";//3
                    inputText += sensor.ThoiGianDo.ToString("yyyy/MM/dd HH:mm:ss.ff") + "µ";//4
                }
                inputText += sensor.Latitude + "µ";//5
                inputText += sensor.Longitude + "µ";//6
                inputText += sensor.Status + "µ";//7
                var url = DaoHelper.Entities.ImageDuAns.FirstOrDefault(p => p.MaDuAn == sensor.MaDuAn && p.Avatar == true);
                if (url != null)
                    inputText += url.ImageUrl + "µ"; //8
                else
                    inputText += "http://geotechnical.vn:8888/Icon/long_bien_bridge.jpg" + "µ";
                inputText += sensor.MaDuAn + "µ";//9
                inputText += sensor.MaSensor;//10
                listInputText += inputText + "€";
            }

            Session[SessionConst.SES_HD_FIELD_SENSOR] = listInputText.Trim('€');
            TextSource.Value = listInputText.Trim('€');
            #endregion

        }
        void DisplayDuan()
        {
            var cu = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;

            var data = (from d in DaoHelper.Entities.PhanQuyenDuAns
                        join s in DaoHelper.Entities.DuAns on d.MaDuAn equals s.MaDuAn
                        where (d.UserName.Equals(cu))
                        select s).ToList();
            Session[SessionConst.SES_GRL_DUAN] = data;
            grlDuAn.DataSource = data;
            grlDuAn.DataBind();

           var listInputText = "";

            foreach (var da in data)
            {
                var inputText = "";
                inputText += da.MaDuAn + "µ";//0
                inputText += da.TenDuAn + "µ";//1
                inputText += da.Latitude + "µ";//2
                inputText += da.Longitude + "µ";//3
                var url = DaoHelper.Entities.ImageDuAns.FirstOrDefault(p => p.MaDuAn == da.MaDuAn && p.Avatar == true);
                if (url != null)
                    inputText += url.ImageUrl + "µ"; //4
                else
                    inputText += "http://geotechnical.vn:8888/Icon/long_bien_bridge.jpg" + "µ";

                var lSensor = "";
                var sensor = (from s in DaoHelper.Entities.Sensors
                              join h in DaoHelper.Entities.SensorLatestValues on s.MaSensor equals h.MaSensor into svl
                              join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                              from sv in svl.DefaultIfEmpty()
                              where (t.Status == 0 && t.MaDuAn == da.MaDuAn)
                              select new
                              {
                                  s.TenSensor,
                                  s.MaSensor,
                                  GiaTri = (sv == null ? -9999 : sv.GiaTri)
                              }).ToList();


                foreach (var s in sensor)
                {
                    var vSensor = "";
                    vSensor += s.MaSensor + "§";
                    vSensor += s.TenSensor + "§";
                    
                    var giaTri = "Không có giá trị";
                    if (s.GiaTri != -9999)
                    {
                        giaTri = s.GiaTri.ToString();
                    }
                    vSensor += giaTri;
                    /*vSensor += "<a href=" + "../Equipments/EquipmentMornitoring.aspx?r=" + s.MaSensor + "&n=§" +
                                s.TenSensor + "§&d=" + da.MaDuAn + " target=\"_blank\">" + " Biểu đồ" +
                               "</a>" + "    " + "<a href=" + "../Equipments/EquipmentData.aspx?r=" + s.MaSensor + "&n=§" +
                               s.TenSensor + "§&d=" + da.MaDuAn + " target=\"_blank\">" + "Dữ liệu" + "</a>";*/
                    lSensor += vSensor + "£";
                }
                inputText += lSensor + "µ";//5
                listInputText += inputText + "€";

            }
            Session[SessionConst.SES_HD_FIELD_DUAN] = listInputText;
            ProjectList.Value = listInputText;
        }
        
        protected void btpopOk_Click(object sender, EventArgs e)
        {
           
            if (FileUpload1.HasFile)
            {
                string[] validFileTypes = { "bmp", "gif", "png", "jpg", "jpeg" };
                string ext = Path.GetExtension(FileUpload1.PostedFile.FileName).Trim('.');
                if (validFileTypes.Contains(ext))
                {
                    if (FileUpload1.PostedFile.ContentLength <= 102400)
                    {
                        var cu = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
                        var maDa = Convert.ToInt32(HidenMaDa.Value);
                        if (!UserHelper.CheckQuyen(cu, maDa))
                        {
                            ErroLbel.Text = "Bạn không có quyền thay đổi hình ảnh!";
                            return;
                        }
                        string folder = "../UserImages/" +
                                        ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
                        string abc = Server.MapPath(folder);
                        if (!Directory.Exists(abc))
                        {
                            Directory.CreateDirectory(abc);
                        }
                        string fileNam = FileUpload1.FileName.Replace(";", "1").Replace("€", "1").Replace("£", "1");
                        FileUpload1.SaveAs(abc + "\\" + fileNam);
                        string file = folder + "/" + fileNam;

                       
                        var img = DaoHelper.Entities.ImageDuAns.FirstOrDefault(p => p.MaDuAn == maDa && p.Avatar == true);
                        if (img == null)
                        {
                            var pt = new ImageDuAn
                            {
                                Avatar = true,
                                ImageUrl = file,
                                MaDuAn = maDa,
                                ChuThich = txtChuThich.Text
                            };
                            DaoHelper.Entities.ImageDuAns.Add(pt);
                        }
                        else
                        {
                            img.ImageUrl = file;
                        }
                        DaoHelper.Entities.SaveChanges();
                        PopUpImage.ShowOnPageLoad = false;
                        DisplayDuan();
                    }
                }
            }
        }

        protected void CbChoiceLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(CbChoiceLayer.SelectedIndex==0)
                Response.Redirect("../Equipments/EquipmentDefault.aspx?d=0");
            else
            {
                Response.Redirect("../Equipments/EquipmentDefault.aspx?d=1");
            }
        }
    }
}